<?php

namespace App\Api\Services;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Api\Models\SmsLogModel;
use Illuminate\Support\Facades\Redis;

class SmsService
{
    /**
     * 短信验证码生成
     * @param $length
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/7 15:51
     * @return int
     */
    static public function code($length = 6) {
        return mt_rand(pow(10,($length-1)), pow(10,$length)-1);
    }

    /**
     * 发送短信验证码
     * @param $mobile
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/7 15:51
     * @return array|void
     */
    static public function sendCode($mobile, $type) {
        AlibabaCloud::accessKeyClient(config('app.sms_key'), config('app.sms_secret'))
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        $code = SELF::code();

        try {
            //调用阿里云短信平台接口发送短信
            $info = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => config('app.sign_name'),
                        'TemplateCode' => config('app.template_id'),
                        'TemplateParam' => json_encode(['code' => $code]),
                    ],
                ])
                ->request();

            $result = $info->toArray();

            if($result['Code'] == 'OK') {
               if($type) {
                   //为验证码设置存活时间-----存活时间为五分钟-登录用
                   Redis::setex($mobile.'_mobile_login', 300, $code);
               }
               else {
                   //为验证码设置存活时间-----存活时间为五分钟-修改验证码用
                   Redis::setex($mobile.'_change_pwd', 300, $code);
               }

                SmsLogModel::insertGetId([
                    'mobile' => $mobile,
                    'code' => $code,
                    'scene' => 0,
                    'create_at' => time()
                ]);

                return ['code' => 0,'msg' => '验证码已成功发送，请注意查收', 'data' => ''];
            }
            else {
                return ['code' => 101,'msg' => '验证码未能成功发送，请稍后重试', 'data' => ''];
            }
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}
